#include <fcntl.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/time.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <linux/videodev2.h>
#include <rga/RockchipRga.h>
#include <QImage>

#include <sys/ioctl.h>

#include <rga/im2d.hpp>
#include <rga/im2d_type.h>
#include <rga/RgaUtils.h>
#include <rga/rga.h>

#include "dma_alloc.h"

extern "C" {
#include "drm_display.h"
}
struct buffer {
        void *start;
        size_t length;
        struct v4l2_buffer v4l2_buf;
};
static unsigned int n_buffers;



#define FBPOOL_MAGIC "FBPL"

#define FPS_UPDATE_INTERVAL 60
#define ERR(...) do { fprintf(stderr, __VA_ARGS__); } while (0)
#define FMT_NUM_PLANES 1
#define BUFFER_COUNT 3
int first = 0;
int fd = -1;
RockchipRga *rga;
bo_t bo_dst;
bo_t bo_src;
rga_info_t rga_info_src;
rga_info_t rga_info_dst;
char *cap_buf[BUFFER_COUNT];
char *video_buf;
char *resize1024x768_buf;
char *resize1440x1080_buf;

int cap_dma_fd[BUFFER_COUNT], video_dma_fd, resize1440x1080_fd, resize1080x768_fd;
rga_buffer_t src[BUFFER_COUNT] = {};
rga_buffer_t video = {};
rga_buffer_t resize1440x1080 = {};

rga_buffer_t resize1080x768 = {};

rga_buffer_handle_t cap_handle[BUFFER_COUNT], video_handle,resize1440x1080_handle , resize1024x768_handle;

int cap_width, cap_height, cap_format;
int resize_width, resize_height, resize_format;
int video_width, video_height, video_format;
int cap_buf_size, video_buf_size,resize_buf_size;
#define CLEAR(x) memset(&(x), 0, sizeof(x))

static int xioctl(int fh, int request, void *arg)
{
        int r;
        do {
                r = ioctl(fh, request, arg);
        } while (-1 == r && EINTR == errno);
        return r;
}

static void log_fps(void) {
    struct timeval tv;
    uint64_t curr_time;
    float fps;

    static uint64_t last_fps_time = 0;
    static unsigned frames = 0;

    if (!last_fps_time) {
        gettimeofday(&tv, NULL);
        last_fps_time = tv.tv_sec * 1000 + tv.tv_usec / 1000;
    }

    if (++frames % FPS_UPDATE_INTERVAL)
        return;

    gettimeofday(&tv, NULL);
    curr_time = tv.tv_sec * 1000 + tv.tv_usec / 1000;

    fps = 1000.0f * FPS_UPDATE_INTERVAL / (curr_time - last_fps_time);
    last_fps_time = curr_time;

    printf("[FBPOOL] FPS: %6.1f || Frames: %u\n", fps, frames);
}
int open_video(void)
{
     fd = open("/dev/video0", O_RDWR /* required */ /*| O_NONBLOCK*/, 0);

    if (-1 == fd) {
		printf("open video err\n");
    	return -1;
    }

    return 0;

}
static void init_rga()
{
    printf("init rga\n");
    cap_width = 1920;
    cap_height = 1080;
    cap_format = RK_FORMAT_BGR_888;

    resize_width = 1440;
    resize_height = 1080;
    resize_format = RK_FORMAT_BGR_888;

    video_width = 1920;
    video_height = 1080;
    video_format = RK_FORMAT_RGB_888;
    cap_buf_size = cap_width * cap_height * get_bpp_from_format(cap_format);
    video_buf_size = video_width * video_height * get_bpp_from_format(video_format);
    resize_buf_size = 1440 * 1080 * get_bpp_from_format(resize_format);
    printf("%d %d \n",cap_buf_size,video_buf_size);
}

static void init_display_buf()
{
    int ret = 0;
    int i;
        int  n1024x768len = 1024*768*3;
    for(i = 0; i < BUFFER_COUNT; i++) {
        ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, cap_buf_size, &cap_dma_fd[i], (void **)&cap_buf[i]);
        if (ret < 0) {
            printf("alloc cap_buf dma_heap buffer failed!\n");
	    return;
        }

        cap_handle[i] = importbuffer_fd(cap_dma_fd[i], cap_buf_size);

         if(cap_handle[i] == 0) {
                 printf("import cap_handle error!\r");
                 goto free_buf;
       }
        printf("cam_dma_fd[%d] = %d\n",i,cap_dma_fd[i]);
    	src[i] = wrapbuffer_handle(cap_handle[i], cap_width, cap_height, cap_format);
    }

    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, video_buf_size, &video_dma_fd, (void **)&video_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
       goto free_buf;
    }

    video_handle = importbuffer_fd(video_dma_fd, video_buf_size);
    if (video_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }

    video = wrapbuffer_handle(video_handle, video_width, video_height, video_format);


    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, resize_buf_size, &resize1440x1080_fd, (void **)&resize1440x1080_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
        return; 
    }

    resize1440x1080_handle = importbuffer_fd(resize1440x1080_fd, resize_buf_size);
    if (resize1440x1080_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }

    resize1440x1080 = wrapbuffer_handle(resize1440x1080_handle, 1440, 1080, resize_format);



    ret = dma_buf_alloc(DMA_HEAP_UNCACHE_PATH, n1024x768len, &resize1080x768_fd, (void **)&resize1024x768_buf);
    if (ret < 0) {
        printf("alloc video dma_heap buffer failed!\n");
        return;
    }

    resize1024x768_handle = importbuffer_fd(resize1080x768_fd, n1024x768len);
    if (resize1024x768_handle == 0) {
        printf("import video_handle error!\n");
        goto free_buf;
    }
    resize1080x768 = wrapbuffer_handle(resize1024x768_handle, 1024, 768, RK_FORMAT_BGR_888);

    return;
		
free_buf:
    for(i = 0; i < BUFFER_COUNT; i++)
        dma_buf_free(cap_buf_size, &cap_dma_fd[i], cap_buf);

    dma_buf_free(video_buf_size, &video_dma_fd, video_buf);
    dma_buf_free(resize_buf_size, &resize1440x1080_fd, resize1440x1080_buf);
    dma_buf_free(n1024x768len, &resize1080x768_fd, resize1024x768_buf);
}
static void init_mmap(void)
{
    struct v4l2_requestbuffers req;

    CLEAR(req);

    req.count = BUFFER_COUNT;
    req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    req.memory = V4L2_MEMORY_DMABUF;

    if (-1 == xioctl(fd, VIDIOC_REQBUFS, &req)) {
		printf("reqbuf err\n");
		return;
    }

    if (req.count !=  BUFFER_COUNT) {
		printf("buf not exp\n");
		return;
    }
    for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
        struct v4l2_buffer buf;
        struct v4l2_plane planes[FMT_NUM_PLANES];
        CLEAR(buf);
        CLEAR(planes);

        buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
        buf.memory = V4L2_MEMORY_DMABUF;
        buf.index = n_buffers;
		
        buf.m.planes = planes;
        buf.length = FMT_NUM_PLANES;

        if (-1 == xioctl(fd, VIDIOC_QUERYBUF, &buf))
                printf("VIDIOC_QUERYBUF err\n");

        buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
        buf.m.planes[0].length = cap_width * cap_height * 3;
	//buf.m.fd = cap_dma_fd[n_buffers];
        if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
			printf("qbuf err\n");

    }
}

static void init_device(void)
{
    struct v4l2_capability cap;
    struct v4l2_format fmt;

    init_rga();

    if (-1 == xioctl(fd, VIDIOC_QUERYCAP, &cap)) {
    	printf("is no V4L2 devicen\n");
		return;
    }

    if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE) &&
            !(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE_MPLANE)) {
			printf("no support cap\n");
			return;
    }

    if (!(cap.capabilities & V4L2_CAP_STREAMING)) {
			printf("no support stream\n");
			return;
    }
    
    CLEAR(fmt);
    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    fmt.fmt.pix.width = cap_width;
    fmt.fmt.pix.height = cap_height;
    fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_RGB24;
    fmt.fmt.pix.field = V4L2_FIELD_NONE;

    if (-1 == xioctl(fd, VIDIOC_S_FMT, &fmt)) {
			printf("no support fmt\n");
			return;
    }



    init_display_buf();

    init_mmap();
}

static void start_capturing(void)
{
    enum v4l2_buf_type type;

    type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    if (-1 == xioctl(fd, VIDIOC_STREAMON, &type))
	    printf("stream on err\n");
	printf("start succ\n");
}

static void process_buffer(int i)
{

#if 1
    int ret, col;

    im_rect  croprect;
    croprect.x = 448;
    croprect.y = 156;
    croprect.width = 1024;
    croprect.height = 768;

   // QImage visiImg = QImage((uchar *)cap_buf[i],1920, 1080, QImage::Format_RGB888);
   // visiImg.save("org.png");


    ret = imcrop(src[i], resize1080x768, croprect);

   // QImage img1024x768 = QImage((uchar *)resize1024x768_buf,1024, 768, QImage::Format_RGB888);
   // img1024x768.save("1024.png");

    ret = imresize(resize1080x768,resize1440x1080,0,0);

   // QImage img1440 = QImage((uchar *)resize1440x1080_buf,1440, 1080, QImage::Format_RGB888);
    //img1440.save("1440.png");

    for(i= 0; i<1080; i++)
    {//all mov 1076 line
        memcpy(video_buf+  1920*(i)*3 + 240*3,  resize1440x1080_buf + i*1440*3 , 1440*3);
    }

    //QImage outImg = QImage((uchar *)video_buf,1920, 1080, QImage::Format_RGB888);

    //outImg.save("out.png");
   //  outImg.save("out.png");
   //QImage img = QImage("/root/a1.png");

   // img = img.convertToFormat(QImage::Format_RGB888);

   // memcpy(video_buf,img.bits(),1920*1080*3);

    drm_render(video_buf, 24,
                  1920, 1080, 1920*3);

#endif

}

static int read_frame()
{
    struct v4l2_buffer buf;
    struct v4l2_plane planes[FMT_NUM_PLANES];
    int i, bytesused;

    CLEAR(buf);
    CLEAR(planes);

    buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
    buf.memory = V4L2_MEMORY_DMABUF;
    buf.m.planes = planes;
    buf.length = FMT_NUM_PLANES;

    if (-1 == xioctl(fd, VIDIOC_DQBUF, &buf))
	    printf("err dqbuf\n");


    i = buf.index;

    bytesused = buf.bytesused;
    process_buffer(i);

    //buf.m.planes[0].m.fd = cap_dma_fd[n_buffers];
    //buf.m.planes[0].length = cap_width * cap_height * 3;
    if (-1 == xioctl(fd, VIDIOC_QBUF, &buf))
	    printf("err qbuf\n");

    return 1;
}


#include <sys/resource.h>

int main(int argc, char **argv)
{
    int size = 0;
    int i,j;

    //int priority = 10; // 范围从-20到19，越高表示越高优先级
    //if (setpriority(PRIO_PROCESS, 0, priority) == -1) {
    //      perror("setpriority");
    //      return 1;
    //}

    //int newPrio = nice(-19);
    //printf("new priority is %d",newPrio);

    pid_t pid = getpid();

    char cCommand[256] = {0};
    sprintf(cCommand,"chrt -p 99 %d",pid);
    system(cCommand);

    printf("start open video ");
    open_video();

    printf("start init capture ");
    init_device();
    start_capturing();

    if (drm_init(2, 24, 1920, 1080) < 0) {
        fprintf(stderr, "init drm failed\n");
        return -1;
    }

    while (1)
    {
           fd_set fds;
           struct timeval tv;
           int r;
           int  fd_max = 0;



           FD_ZERO(&fds);



           FD_SET(fd, &fds);
           if(fd > fd_max)
           {
               fd_max = fd;
           }

           // Timeout
           tv.tv_sec = 2;
           tv.tv_usec = 0;

           r = select(fd_max + 1, &fds, NULL, NULL, &tv);
           if (-1 == r) {
               if (EINTR == errno)
                   return -1;

           }

           if (0 == r)
           {
                return -1;
           }


           if (FD_ISSET( fd, &fds ))
           {
                read_frame();
           }

    }

    //drm_deinit();

    for(i = 0; i < BUFFER_COUNT; i++)
        dma_buf_free(cap_buf_size, &cap_dma_fd[i], cap_buf);

    dma_buf_free(video_buf_size, &video_dma_fd, video_buf);
    dma_buf_free(resize_buf_size, &resize1440x1080_fd, resize1440x1080_buf);

    dma_buf_free(1024*768*3, &resize1080x768_fd, resize1024x768_buf);

    if(fd > 0)
    {
       close(fd);
    }

    return 0;
}
